package com.huiminpay.merchant.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.PhoneUtil;
import com.huiminpay.common.cache.util.StringUtil;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.merchant.api.IMerchantService;
import com.huiminpay.merchant.common.util.SecurityUtil;
import com.huiminpay.merchant.convert.MerchantDetailConvert;
import com.huiminpay.merchant.convert.MerchantRegisterConvert;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.merchant.dto.MerchantDTO;
import com.huiminpay.merchant.service.SmsService;
import com.huiminpay.merchant.vo.MerchantDetailVO;
import com.huiminpay.merchant.vo.MerchantRegisterVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@ApiResponses({
        @ApiResponse(code = 200, message = "请求成功"),
        @ApiResponse(code = 400, message = "请求参数没填好"),
        @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
})
@Slf4j
public class MerchantController {

    @Reference
    IMerchantService merchantService;

    @Autowired
    private SmsService smsService;

    @Reference
    AppService appService;

    @Autowired
    OSS oss;
    @Value("${oss.aliyun.bucket}")
    private String bucket;
    @Value("${oss.aliyun.domain}")
    private String domain;


    @GetMapping("my/merchants")
    public MerchantDTO queryMerchantById() {
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO merchantDTO = merchantService.queryMerchantById(merchantId);
        return merchantDTO;
    }

    @GetMapping("sms")
    public String getSMSCode(@RequestParam String phone) {
        log.info("向手机号:{}发送验证码", phone);
        return smsService.sendSms(phone);
    }

    @ApiOperation("注册商户")
    @ApiImplicitParam(name = "merchantRegister", value = "注册信息", required = true, dataType =
            "MerchantRegisterVO", paramType = "body")
    @PostMapping("/merchants/register")
    public MerchantRegisterVo registerMerchant(@RequestBody MerchantRegisterVo merchantRegister) {

        // 校验验证码
        smsService.checkVerifiyCode(merchantRegister.getVerifiykey(),
                merchantRegister.getVerifiyCode());
        // 注册商户
       /*  MerchantDTO merchantDTO = new MerchantDTO();
        merchantDTO.setUsername(merchantRegister.getUsername());
        merchantDTO.setMobile(merchantRegister.getMobile());
        merchantDTO.setPassword(merchantRegister.getPassword());
        merchantService.createMerchant(merchantDTO); */
// 1.校验
        if (merchantRegister == null) {
            throw new BusinessException(CommonErrorCode.E_100108);
        }
// 手机号非空校验
        if (StringUtil.isBlank(merchantRegister.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100112);
        }
// 校验手机号的合法性
        if (!PhoneUtil.isMatches(merchantRegister.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100109);
        }
// 联系人非空校验
        if (StringUtil.isBlank(merchantRegister.getUsername())) {
            throw new BusinessException(CommonErrorCode.E_100110);
        }
// 密码非空校验
        if (StringUtil.isBlank(merchantRegister.getPassword())) {
            throw new BusinessException(CommonErrorCode.E_100111);
        }
// 验证码非空校验
        if (StringUtil.isBlank(merchantRegister.getVerifiyCode()) ||
                StringUtils.isBlank(merchantRegister.getVerifiykey())) {
            throw new BusinessException(CommonErrorCode.E_100103);
        }
        MerchantDTO merchantDTO = MerchantRegisterConvert.getInstance.voToDto(merchantRegister);
        merchantService.createMerchant(merchantDTO);
        return merchantRegister;
    }

    @PostMapping("upload")
    @ApiOperation("上传证件照")
    public String upload(@ApiParam(value = "证件照", required = true) @RequestParam("file") MultipartFile multipartFile) throws IOException {
        String fileName = System.currentTimeMillis() + "";
        String originalFilename = multipartFile.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.indexOf("."));
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName + ext, multipartFile.getInputStream());
            oss.putObject(putObjectRequest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_100106);
        }
        return domain + fileName + ext;
    }

    @ApiOperation("资质申请")
    @PostMapping("/my/merchants/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantInfo", value = "商户认证资料", required = true, dataType = "MerchantDetailVO", paramType = "body")
    })
    public void saveMerchant(@RequestBody MerchantDetailVO merchantInfo) {
        // 解析token，取出当前登录商户的id
        Long merchantId = SecurityUtil.getMerchantId();

        // Long merchantId,MerchantDTO merchantDTO
        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.vo2dto(merchantInfo);
        merchantService.applyMerchant(merchantId, merchantDTO);
    }

    /**
     * 根据商户id 查询该商户下的应用列表
     * @return java.util.List<com.huiminpay.merchant.api.dto.AppDTO>
     */
    @ApiOperation("查询商户下的应用列表")
    @GetMapping(value = "/my/apps")
    public List<AppDTO> queryMyApps(){
        Long merchantId = SecurityUtil.getMerchantId();
        return appService.queryAppByMerchant(merchantId);
    }

}